import React from 'react';
import {routerShape} from 'react-router';
import { inject, observer } from 'mobx-react';
import { WeaErrorPage, WeaTools,WeaLocaleProvider,WeaTop,WeaTab,WeaRightMenu,WeaReportGroup} from 'ecCom';
import FnaPermission from '../../public/FnaPermission';
import {getPrimaryButton} from '../../public/FnaButton';
import {fnaWarningTip} from '../../public/FnaMessage'
//import SaveToTemple from './SaveToTemple';
import cloneDeep from 'lodash/cloneDeep';
import {toJS}  from 'mobx'
const getLabel = WeaLocaleProvider.getLabel;

/**
 * 自定义报表
 */
@inject('customReportStore')
@observer
class CustomReport extends React.Component {
	static contextTypes = {
        router: routerShape
    }

	constructor(props) {
		super(props);
	}

	componentDidMount() {
		const { customReportStore } = this.props;
		const { initDatas } = customReportStore;
		const { reportId,accountIds } = this.props.location.query;

		initDatas({reportid:reportId,accountId:accountIds.replace(/_/g,',')});
	}
	
	componentWillReceiveProps(nextProps) {
		
	}
	
	shouldComponentUpdate(nextProps, nextState) {
		
		return true;
	}

	componentWillUnmount() {
		//组件卸载时一般清理一些状态

	}

	render() {
		const { customReportStore } = this.props;
		const { reportName } = this.props.location.query;
		const { loading,hasRight,reportConfig } = customReportStore;                                                                                                                               
		let title = <span><span>{reportName}</span></span>
		
		return (
			<div style={{height: '100%'}}>
			  {hasRight == 1 && <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@6kq3vt`} 
			  	datas={this.getRightMenu()}
			  	collectParams={{favname:reportName, favouritetype:5}}
			   >
				<WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@ny0m4m`}
					title={title}
					loading={loading}
					icon={<i className='icon-coms-Finance'/>}
					iconBgcolor='#f14a2d'
					buttons={this.getTopRightButton(this.props.ecId || '')}
					buttonSpace={10}
					showDropIcon={true}
					dropMenuDatas={this.getRightMenu()}
				>
				
				{/* <WeaTab
					datas={tab}
					keyParam="viewcondition"  //主键
					selectedKey={selected}
					counts={tabCount}
					onChange={this.switchTab}
				/> */}

				<WeaReportGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaReportGroup@d86zzl`}
					ref={this.initRef}
					config={toJS(reportConfig)}
					hasShowAll={false}//这玩意是个反的,true是展示勾选的,false是展示全部
					onChange={this.doReportGroupChange}
            	/>
                </WeaTop>
             </WeaRightMenu>}
			 {hasRight == 4 && <FnaPermission ecId={`${this && this.props && this.props.ecId || ''}_FnaPermission@kdzqo8`}/>}
			 {/* <SaveToTemple ecId={`${this && this.props && this.props.ecId || ''}_SaveToTemple@n156cc`} visible={visibleTemp} close={()=>{setvisibleTemp(false);}}/> */}
			</div>
		)
	}
	
	initRef = (report) => {
		this.report = report;
	}

	doReportGroupChange = (obj,ids,isFirst) => {

	}
	
	//Top右侧按钮菜单
	getTopRightButton = (ecId) => {
		const { customReportStore } = this.props;
		const { loading,selected } = customReportStore;
		let btns = [];
		//btns.push(getPrimaryButton(this.doSearchMulit,loading,'多搜索'));
		btns.push(getPrimaryButton(this.doSearCh,loading,getLabel(197,'搜索'),ecId+'_Search_CustomReport'));
		btns.push(getPrimaryButton(this.doReset,loading,getLabel(2022,'重置'),ecId+'_Search_CustomReport'));

		// if(selected == 0){
		// 	btns.push(getPrimaryButton(this.saveToTemple,loading,getLabel(127365,'存为模板')));
		// }

		// if(selected != 0){
		// 	btns.push(getPrimaryButton(this.doSave,loading,getLabel(86,'保存')));
		// 	btns.push(getPrimaryButton(this.saveToTemple,loading,getLabel(131623,'另存为')));
		// 	btns.push(getPrimaryButton(this.doDelete,loading,getLabel(91,'删除')));
		// }

		return btns;
	}

	/**
	*获取右键菜单
	*/
	getRightMenu = () => {
		const { customReportStore } = this.props;
		const { loading,selected } = customReportStore;
		let btns = [];

    	 btns.push({
	            key:"search",
				icon: <i className='icon-coms-search'/>,
				disabled:loading,
	            content:getLabel(197,'搜索'),
	            onClick:()=>{this.doSearCh();}
		 });
		 btns.push({
			key:"reset",
			icon: <i className='icon-coms-Reset'/>,
			disabled:loading,
			content:getLabel(2022,'重置'),
			onClick:()=>{this.doReset()}
		});

		/*
		if(selected == 0){
			btns.push({
				key:"saveToTemple",
				icon: <i className='icon-coms-Preservation'/>,
				disabled:loading,
				content:getLabel(127365,'存为模板'),
				onClick:()=>{this.saveToTemple()}
			});
		}

		if(selected != 0){
			btns.push({
	            key:"save",
				icon: <i className='icon-coms-Preservation'/>,
				disabled:loading,
	            content:getLabel(86,'保存'),
	            onClick:()=>{this.doSave();}
		 	});
			btns.push({
				key:"saveto",
				icon: <i className='icon-coms-Preservation'/>,
				disabled:loading,
				content:getLabel(131623,'另存为'),
				onClick:()=>{this.doReset()}
			});
			btns.push({
	            key:"delete",
				icon: <i className='icon-coms-Batch-delete'/>,
				disabled:loading,
	            content:getLabel(91,'删除'),
	            onClick:()=>{this.doSearCh();}
			});
		}
		*/

	    return btns;
	}

	//主tab切换
	switchTab = (index) => {
		const { customReportStore } = this.props;
		const { setSelected} = customReportStore;

		setSelected(index);
	}

	//单账套搜索
	doSearCh = () => {
		const { customReportStore } = this.props;
		const { reportId,accountIds,typeIdComb,approvalIds,reportName } = this.props.location.query;
		let params = {reportId:reportId,accountId:accountIds,typeIdComb:typeIdComb,approvalId:approvalIds};
		let items = this.report.get();

		let checkArr = Object.keys(items).filter((item,index)=>{
			if(items[item].checked){
                return true;
            }else{
                return false;
            }
		});

		let selectfieldids = checkArr.join(',');
		// if(!selectfieldids){//没有勾选就不查询
		// 	fnaWarningTip(getLabel(505669,'请选择查询的条件'));
        //     return '';
		// }
		params.selectfieldids = selectfieldids;

		checkArr.forEach((item,index)=>{
            params = {...params,...items[item].value}
        })

		//查询数据存储
		for(let key in params){
			window.sessionStorage.setItem(key,params[key]);
		}


		let query = {reportId:reportId,accountId:accountIds,typeIdComb:typeIdComb,approvalId:approvalIds,reportName:reportName};
		this.context.router.push({
            pathname : "/main/fnaMulit/showReport",
            query : {
                ...query
            }
        });
	}

	//多账套搜索
	doSearchMulit = () => {
		const { customReportStore } = this.props;
		const { reportId,typeIdComb,accountIds,approvalIds,reportName } = this.props.location.query;
		const { reportConfig } = customReportStore;
		let params = {reportId:reportId,typeIdComb:typeIdComb};
		let items = this.report.get();
		let configs = toJS(reportConfig); 
		//accountid1_1,accountid1_2 accountid2_1,accountid2_2
		let checkArr = Object.keys(items).filter((item,index)=>{
			if(items[item].checked){
                return true;
            }else{
                return false;
            }
		});

		let selectfieldids = checkArr.join(',');
		if(!selectfieldids){//没有勾选就不查询
			fnaWarningTip(getLabel(505669,'请选择查询的条件'));
            return '';
		}

		//勾选了几个账套
		let accountSelect = [];
		for(let item of checkArr){
			let arrays = item.split('_');

			if(!accountSelect.includes(arrays[0])){//不包含就添加
				accountSelect.push(arrays[0]);
			}
		}

		//每个账套对应的条件勾选
		let selectAccountObjs = [];//[{accountId:'qazqaz',keys[1,2]}]
		for(let accountId of accountSelect){
			let selectkeysInAccount = [];
			configs.map((config,index)=>{
				if(accountId == config['accountId']){//config 应该具备accountId
					selectkeysInAccount.push(config.key.split('_')[1]);
				}
			});

			selectAccountObjs.push({
				accountId:accountId,
				keys:selectkeysInAccount
			});
		}

		//遍历拼接数据
		selectAccountObjs.map((outeritem,outerIndex)=>{
			outeritem.keys.forEach((selectKey,keyIndex)=>{
				let param = {};
				let item = items[outeritem.accountId+'_'+selectKey].value;
				for(let key of Object.keys(item)){//遍历选中的表单数据
					param[key+outerIndex] = item[key];
				}

				params = {...params,...param};
			});

			// let accountIdTem = accountIds+'_'+'c096e927991947428d3fa7424be443a6';
			// let approvalIdsTem = approvalIds+'_'+approvalIds;
			let queryAccountIds = accountIds.split('_');//切割
			let queryApprovalIds = approvalIds.split('_');
			for(let index = 0 ; index < queryAccountIds.length ; index++){
				if(queryAccountIds[index] == outeritem.accountId){
					let approvalIds = {};
					approvalIds['approvalIds'+outerIndex] = queryApprovalIds[index];//取出当前账套 url的节点id
					params = {...params,...selectfieldids,...accountId,...approvalIds};
				}
			}

			let selectfieldids = {};
			let accountId = {};
			accountId['accountId'+outerIndex] = outeritem.accountId;
			selectfieldids['selectfieldids'+outerIndex] = outeritem.keys.join(',');
			

			params = {...params,...selectfieldids,...accountId};
		});

		for(let key in params){
			window.sessionStorage.setItem(key,params[key]);
		}

		// console.log('params',params);
		let query = {reportId:reportId,accountId:accountIds,typeIdComb:typeIdComb,approvalId:approvalIds,reportName:reportName};
		this.context.router.push({
			pathname : "/main/fnaMulit/showReport",
			query : {
                ...query
            }
        });
	}

	//重置
	doReset = () => {
		const { customReportStore } = this.props;
		const { reportConfig,setReportConfig } = customReportStore; 
		const curReportConfig = cloneDeep(mobx.toJS(reportConfig));

		//只重置表单数据,不重置选中
		setReportConfig([]);
        setTimeout(()=>{
			setReportConfig(curReportConfig);
        },0);
	}



	/*****************暂时不要****************** */
	//存为模板
	saveToTemple = () => {
		const { customReportStore } = this.props;
		const { saveToTemple} = customReportStore;
		saveToTemple(true);
	}

	//保存
	doSave = () => {
		const { customReportStore } = this.props;
		const { setvisibleTemp} = customReportStore;
		setvisibleTemp(true);
	}

	//删除
	doDelete = ()=>{
		const { customReportStore } = this.props;
		const { doDelete} = customReportStore;
		//doDelete();
	}
}


export default WeaTools.tryCatch(React,
	props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@x54lvu`} msg={ props.error ? props.error : getLabel(385218,'对不起,该页面异常,请联系管理员!')} />,
	{error: ""}
)(CustomReport);




